package the_art_of_java_concurrency_programming.concurrent.Thread;

import java.util.concurrent.TimeUnit;

/**
 * @Author: 李浩然
 * @Date: 2021/4/20 10:54 上午
 */
public class Profiler {
    //第一次get（）方法调用时会进行初始化（如果set没有被调用），每个线程会调用1次
    private static final ThreadLocal<Long> TIME_THREADLOCAL = new ThreadLocal<Long>() {
        protected Long initialValue() {
            return System.currentTimeMillis();
        }
    };

    public static final void begin() {
        TIME_THREADLOCAL.set(System.currentTimeMillis());
    }

    public static final long end() {
        return System.currentTimeMillis() - TIME_THREADLOCAL.get();
    }

    public static void main(String[] args) throws InterruptedException {
        Profiler.begin();
        TimeUnit.SECONDS.sleep(3);
        System.out.println("Cost: " + Profiler.end() + " mills");
    }
}
